package classloader;

import java.io.*;

/**
 * 我的自定义文件类加载器
 *
 * @author dingwen
 * @date 2021/08/29
 */
public class MyFileClassLoader extends ClassLoader {
    /**
     * 被加载类所在目录
     */
    private String directory;

    public MyFileClassLoader(ClassLoader parent, String directory) {
        super(parent);
        this.directory = directory;
    }

    public MyFileClassLoader(String directory) {
        this.directory = directory;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            // 把类名转为目录
            String file = directory + File.separator + name.replace(".", File.separator) + ".class";
            // 构建输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            // 构建字节输出流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = fileInputStream.read(buf)) != -1) {
                byteArrayOutputStream.write(buf, 0, len);
            }
            //读取到到二进制数据
            byte[] data = byteArrayOutputStream.toByteArray();
            fileInputStream.close();
            byteArrayOutputStream.close();
            return defineClass(name, data, 0, data.length);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        MyFileClassLoader myFileClassLoader = new MyFileClassLoader("/Users/dingwen/Documents/study/java8-study/src/");
        Class<?> clazz = myFileClassLoader.findClass("classloader.URLClassLoaderDemo");
        clazz.newInstance();
    }
}
